package shs

import (
	"io"
	"os"

	"github.com/edsrzf/mmap-go"
)

func writeFile(f *os.File, offset int64, content []byte) error {
	_, err := f.Seek(offset, io.SeekStart)
	if err != nil {
		return err
	}
	err = f.Truncate(int64(PageSize))
	if err != nil {
		return err
	}
	m, err := mmap.Map(f, mmap.RDWR, 0)
	if err != nil {
		return err
	}
	defer m.Unmap()

	// m acts as a writable slice of bytes that is a view into the open file, notes.txt.
	// It is sized to the file contents automatically.
	copy(m, content)

	return nil
}

func loadFile(f *os.File, offset int64, do func([]byte) error) error {
	_, err := f.Seek(offset, io.SeekStart)
	if err != nil {
		return err
	}
	err = f.Truncate(int64(PageSize))
	if err != nil {
		return err
	}

	m, err := mmap.Map(f, mmap.RDWR, 0)
	if err != nil {
		return err
	}
	defer m.Unmap()

	// m acts as a writable slice of bytes that is a view into the open file, notes.txt.
	// It is sized to the file contents automatically.
	return do(m)
}
